package com.het.monitor.task;

import com.het.monitor.common.AreaType;
import com.het.monitor.config.Apps;
import com.het.monitor.task.model.AlertApp;
import com.het.monitor.task.model.AppConf;
import com.het.monitor.service.AlertAppService;
import com.het.monitor.service.AppConfService;
import com.het.monitor.util.AESUtil;
import com.het.monitor.util.ConnLinuxServerUtil;
import com.het.monitor.util.DateUtils;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class ScheduleJobMonitorB {
    @Resource
    AlertAppService alertAppService;
    @Resource
    AppConfService appConfService;
    @Value("${aes.secret}")
    public String secret;
    /**
     * 任务B:监控A域服务是否正常
     * @throws InterruptedException
     */
    @Async
//    @Scheduled(fixedDelay = 1000 * 10)
    @XxlJob("monitorBJobHandler")
    public void taskB() throws InterruptedException {
        log.info("执行监控任务B-开始时间：" + DateUtils.getNowTime(DateUtils.YYY_MM_DD_HH_MM));
        List<AppConf> services = appConfService.getAreaTypeList("B");
        List<AlertApp> alertAppList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(services) && services.size() > 0) {
            ConnLinuxServerUtil connLinuxServerUtil = new ConnLinuxServerUtil();
            services.forEach(app -> {
                Boolean monitorResult = connLinuxServerUtil.monitor(connLinuxServerUtil,app,app.getCheckCmd(), AreaType.B, secret);
                if (!monitorResult) {
                    alertAppList.add(AlertApp.builder().ip(app.getIp()).appJar(app.getAppJar()).appName(app.getAppName()).area_type(app.getAreaType()).build());
                }
            });
            if (alertAppList.size()>0){
                alertAppService.saveOrUpdateBatch(alertAppList);
            }
        };
        log.info("执行监控任务B-结束时间：" + DateUtils.getNowTime(DateUtils.YYY_MM_DD_HH_MM));
    }
}
